/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.yzbdl.lanius.orchestrate.serv.database;

import lombok.extern.slf4j.Slf4j;
import oracle.jdbc.driver.OracleConnection;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.yzbdl.lanius.orchestrate.common.enums.DataBaseTypeEnum;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Objects;
import java.util.Properties;

/**
 * 数据库资源库处理抽象类
 *
 * @author hujian@yzbdl.ac.cn
 * @date 2022-09-20 16:42
 */
@Slf4j
@Component
public class OracleDbRepositoryInvokeHandler extends AbstractDbRepositoryInvokeHandler implements InitializingBean {


    /**
     * 获取Jdbc模板
     * @param jdbcDriverClassName 驱动类名称
     * @return Jdbc模板
     */
    @Override
    public String getJdbcTemplate(String jdbcDriverClassName) {
        return DataBaseTypeEnum.ORACLE.getJdbcUrlTemplate();
    }

    /**
     * 测试数据库连通性；超时时间为10s
     * @param url url
     * @param username 用户名
     * @param password 密码
     * @return 成功与否
     */
    @Override
    public Boolean testConnection(String url, String username, String password) {
        Connection conn = null;
        try {
            Properties props = new Properties();
            props.setProperty("user", username);
            props.setProperty("password", password);
            props.setProperty(OracleConnection
            .CONNECTION_PROPERTY_THIN_NET_CONNECT_TIMEOUT, CONNECT_DB_TIME_OUT);

            conn = DriverManager.getConnection(url, props);
            return conn.isValid(CONNECT_DB_SOCKET_TIME_OUT);
        } catch (Exception e) {
            log.error("数据库{}连接超时！", url, e);
            return false;
        } finally {
            try{
                if(Objects.nonNull(conn)) {
                    conn.close();
                }
            } catch (Exception e){
                log.error("数据库{}关闭超时！", url, e);
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        DbRepositoryFactory.register(DataBaseTypeEnum.ORACLE.getCode(), this);
    }
}
